package com.zjw.zy.utils;


import android.text.TextWatcher;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.zjw.zy.base.ImageEditText;
import com.zjw.zy.ext.EditTextExtKt;

import java.util.Deque;
import java.util.LinkedList;

//todo 字符串回退助手

//待优化
public final class UndoUtils {

    //最多回滚20次
    private static final int MAX_UNDO_COUNT = 20;

    //保证永远大于1
    private final Deque<String> mQueue = new LinkedList<>();

    public UndoUtils(@NonNull String str) {
        mQueue.addLast(str);
    }

    public void markChange(@NonNull String newStr) {
        mQueue.addLast(newStr);

        if (mQueue.size() >= MAX_UNDO_COUNT) {
            mQueue.removeFirst();
        }
    }

    public void markStart(@NonNull String newStr) {
        mQueue.clear();
        mQueue.addLast(newStr);
    }

    public String undo(@NonNull EditText editText, @Nullable TextWatcher watcher) {
        if (canUndo()) {
            mQueue.removeLast();
        }
        //先移除
        editText.removeTextChangedListener(watcher);
        if (editText instanceof ImageEditText) {
            ((ImageEditText) editText).setTextWithImage(mQueue.peekLast());
        } else {
            editText.setText(mQueue.peekLast());
        }
        EditTextExtKt.selectLast(editText);
        //再添加
        editText.addTextChangedListener(watcher);
        return mQueue.peekLast();
    }

    public boolean canUndo() {
        return mQueue.size() > 1;
    }

}
